package com.example.administrator.newproject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v7.app.ActionBarActivity;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Adapter.CityAdapter;
import Bean.CityName;
import sort.CharacterParser;
import sort.MyLetterAlistView;
import sort.PinyinComparator;

public class MainActivity extends ActionBarActivity {
    String path="http://m.jiwu.com/app!cityList.action?v=1&appKey=&deviceType=Android";
    // 搜索内容
    private EditText editText;
    // 城市列表
    private ListView sortListView;
    // 右侧A-Z字母列表
    private MyLetterAlistView letterListView;
    // dialog text
    private TextView overlay;
    // 估计是弹出dialog线程
    private OverlayThread overlayThread;
    // 城市Adapter
    private CityAdapter adapter;
    private Handler handler;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<CityName> SourceDateList;
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private String[] str;
    private String cityName;
    private JsonObjectRequest jsonObjectRequest;
    private RequestQueue requestQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().hide();
        initView();
    }

    public void initView() {
        handler = new Handler();
        overlayThread = new OverlayThread();
        // 实例化汉字转拼音类
        characterParser =CharacterParser.getInstance();
        // 根据拼音排序
        pinyinComparator = new PinyinComparator();

        editText = (EditText) findViewById(R.id.editText);
        sortListView = (ListView) findViewById(R.id.country_lvcountry);
        ProgressBar bar= (ProgressBar) findViewById(R.id.progressBar5);
        sortListView.setEmptyView(bar);
        letterListView = (MyLetterAlistView) findViewById(R.id.cityLetterListView);
        SourceDateList=new ArrayList<CityName>();
        JsonDownLoad();
        // SourceDateList = filledData(str);
        //  SourceDateList= new ArrayList<SortModel>();

        listView.setEmptyView(bar);

        adapter = new CityAdapter(this, SourceDateList);
        sortListView.setAdapter(adapter);
        initOverlay();
        letterListView
                .setOnTouchingLetterChangedListener(new LetterListViewListener());
        sortListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent i=new Intent();

                i.putExtra("id", SourceDateList.get(position).getiCodeID());
                i.putExtra("name",SourceDateList.get(position).getsName());

                i.setClass(MainActivity.this,SecondActivity.class);

                MainActivity.this.finish();
                startActivity(i);
            }
        });
        // 根据输入框输入值的改变来过滤搜索
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {


            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }
    public void JsonDownLoad(){

        requestQueue = Volley.newRequestQueue(this);
        jsonObjectRequest = new JsonObjectRequest(path,null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {


                try {
                    JSONArray array=response.getJSONArray("cityArray");

                    for (int i = 0; i < array.length(); i++) {

                        JSONObject object2=array.getJSONObject(i);

                        String name=object2.getString("cityName");
                        CityName cityName=new CityName(name);

                        String id=object2.getString("cityId");

                        cityName.setiCodeID(id);
                       // Log.i("jjj",name+"==============");

                        // 汉字转换成拼音
                        String pinyin = characterParser.getSelling(name);
                        //Log.i("jjj",pinyin+"==============");
                        String sortString = pinyin.toUpperCase();

                        //Log.i("jjj",sortString+"==============");
                        if ((sortString!=null)&&(sortString!="")){

                            if (sortString.length()>1){

                                sortString=sortString.substring(0,1);

                            }



                        }

                        Log.i("hahaha",sortString);
                        // Toast.makeText(MainActivity.this,sortString,Toast.LENGTH_LONG).show();
                        // 正则表达式，判断首字母是否是英文字母
                        if (sortString.matches("[A-Z]")) {
                            cityName.setSortLetters(sortString.toUpperCase());
                        } else {
                            cityName.setSortLetters("#");
                        }
                        Collections.sort(SourceDateList, pinyinComparator);
                        SourceDateList.add(cityName);
                        // 根据a-z进行排序源数据

                    }

                    adapter.notifyDataSetChanged();

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(MainActivity.this, "下载失败!", Toast.LENGTH_SHORT).show();

            }
        });


        requestQueue.add(jsonObjectRequest);
    }
    // 右侧A-Z字母监听
    private class LetterListViewListener implements
            MyLetterAlistView.OnTouchingLetterChangedListener {

        @Override
        public void onTouchingLetterChanged(final String s) {
            // 该字母首次出现的位置
            int position = adapter.getPositionForSection(s.charAt(0));
            if (position != -1) {
                sortListView.setSelection(position);
                overlay.setText(SourceDateList.get(position).getSortLetters());
                overlay.setVisibility(View.VISIBLE);
                handler.removeCallbacks(overlayThread);
                // 延迟一秒后执行，让overlay为不可见
                handler.postDelayed(overlayThread, 1500);
            }
        }
    }

    // 初始化汉语拼音首字母弹出提示框
    private void initOverlay() {
        LayoutInflater inflater = LayoutInflater.from(this);
        overlay = (TextView) inflater.inflate(R.layout.overlay, null);
        overlay.setVisibility(View.INVISIBLE);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        WindowManager windowManager = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(overlay, lp);
    }

    // 设置overlay不可见
    private class OverlayThread implements Runnable {

        @Override
        public void run() {
            overlay.setVisibility(View.GONE);
        }

    }

    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
//    private List<SortModel> filledData(String[] date) {
//        List<SortModel> mSortList = new ArrayList<SortModel>();
//
//        for (int i = 0; i < date.length; i++) {
//            SortModel sortModel = new SortModel();
//            sortModel.setName(date[i]);
//            // 汉字转换成拼音
//            String pinyin = characterParser.getSelling(date[i]);
//            String sortString = pinyin.substring(0,1).toUpperCase();
//
//            // 正则表达式，判断首字母是否是英文字母
//            if (sortString.matches("[A-Z]")) {
//                sortModel.setSortLetters(sortString.toUpperCase());
//            } else {
//                sortModel.setSortLetters("#");
//            }
//
//            mSortList.add(sortModel);
//        }
//        return mSortList;
//
//    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<CityName> filterDateList = new ArrayList<CityName>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = SourceDateList;
        } else {
            filterDateList.clear();
            for (CityName sortModel : SourceDateList) {
                String name = sortModel.getsName();
                if (name.indexOf(filterStr.toString()) != -1
                        || characterParser.getSelling(name).startsWith(
                        filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }
    long currnttime=0;

    @Override
    public void onBackPressed() {

        if (System.currentTimeMillis()-currnttime<3000){

            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startMain);

            System.exit(0);//退出程序

        }else{

            currnttime=System.currentTimeMillis();
            Toast.makeText(MainActivity.this, "再按一次退出!", Toast.LENGTH_SHORT).show();

        }

    }

}
